#include "cm_window.hpp"

#ifdef _MSC_VER
#pragma comment(lib, "OpenGL32.lib")
#pragma comment(lib, "GlU32.lib")
#endif

#include <stdexcept>

using namespace ge;

namespace cm {
  int window::_width;
  int window::_height;
  bool window::_created = false;
  color window::_background_color;
  window::drawables window::_drawables;

  window::window(color const & c, int const width, int const height) {
    if(_created)
      throw std::logic_error("Only one instance of class cm::window can be created");
    else
      _created = true;
    _width = width;
    _height = height;
    _background_color = c;

    int argc = 0;
    glutInit(&argc, NULL);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
    glutInitWindowSize(_width, _height);   
    glutInitWindowPosition(200,100);  
    //winID = glutCreateWindow("Crazy Michael"); 
    glutCreateWindow("Crazy Michael"); 

    glutDisplayFunc(display);
    //glutIdleFunc(idle);
    glutReshapeFunc(resize);
    //glutKeyboardFunc(keyboard);  
    glClearColor(c.r, c.g, c.b, 0.0f);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0.0f, _width, 0.0f, _height);
  }

  void window::resize(GLsizei w, GLsizei h) {
    if(w >= 600 && h >=375){
      _width = w;
      _height = h;
    } else
      glutReshapeWindow(w, h);
  }
  
  void window::display() {
    glClear(GL_COLOR_BUFFER_BIT);
    for (drawables::iterator i = _drawables.begin(); i != _drawables.end(); ++i) {
      glColor3f((*i) -> diffuse_color.r, (*i) -> diffuse_color.g, (*i) -> diffuse_color.b);
      glBegin(GL_POLYGON);
        glVertex2f((*i) -> position.x, (*i )-> position.y);
        glVertex2f((*i) -> size(), (*i )-> position.y);
        glVertex2f((*i) -> size(), (*i )-> size());
        glVertex2f((*i) -> position.x, (*i )-> size());
      glEnd();
    }
    glutSwapBuffers();
  }
  
  void window::add(drawable const & drawable_) {
    _drawables.push_back(&drawable_);
  }
  
  void window::start() {
    glutMainLoop();
  }
}
